package com.ylxn.chapter01;

/**
 * 两阶段终止模式
 */
public class demo06 {
    public static void main(String[] args) throws InterruptedException {
        TwoPhaseTermination termination = new TwoPhaseTermination();
        termination.start();
        Thread.sleep(20000);
        termination.stop();
    }
}

class TwoPhaseTermination{
    //监控线程
    private Thread monitor;

    /**
     * 启动线程
     */
    public void start(){
        monitor = new Thread(()->{
            while (true){
                //当前线程是否被打断
                boolean interrupted = Thread.currentThread().isInterrupted();
                if (interrupted){
                    System.out.println("料理后事");
                    //退出线程
                    break;
                }
                try {
                    Thread.sleep(2000);
                    //执行监控记录
                    System.out.println("执行监控记录");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    //重新设置打断标记
                    Thread.currentThread().interrupt();
                }
            }
        },"monitor_start");
        monitor.start();
    }

    /**
     * 停止线程
     */
    public void stop(){
        monitor.interrupt();
    }

}
